<template>
  <DynamicForm :config="dyModalConfig" :questions="dyModalQuestions" ref="modalRef"></DynamicForm>
</template>

<script lang="ts" setup>
import { DynamicForm } from '@/components/public-template';
import { INITSERVE, INPUTSERVE, ITEMSERVE, SELECTSERVE, UPLOADESERVE } from '@/mixins/subject/subject-types';
import { computed, getCurrentInstance, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue';
import indexService from './modalForm.service';
import { Api as ApiArchives } from '@/config/api/archives';
import { findListByBoxId } from '@/config/api/archivesFile';
import { filter } from 'rxjs/operators';

const props = defineProps({
  data: {
    type: Object
  },
  type: {
    type: String,
    default: ''
  },
  // 件号合集，用于查找最大件号
  partNoList: {
    type: Array
  },
  upDate: {
    type: Number
  }
});
const emits = defineEmits(['update:data', 'setPartNoList']);
const state = reactive({
  count: 1
});
const formName = Date.now().toString();
const dyModalConfig: any = {
  name: formName,
  labelCol: 8,
  wrapperCol: 16,
  grid: 6,
  layout: 'vertical',
  cancelSave: true
};
const modalRef = ref(null);
const { proxy }: any = getCurrentInstance();
const dyModalQuestions: any = reactive(indexService.getQuestions(props.type, props.data.toDepartment, props.data?.attachment?.archiveFileId));
initData();

// 初始数据
function initData(rowData = props.data) {
  dyModalQuestions.forEach((item) => {
    if (['filesBoxId', 'partNo'].includes(item.key)) {
      // 当载体类型为实物档案时，档案盒，件号为空，不可编辑
      item.required = rowData.type != 4;
      item.disabled = rowData.type == 4;
    }
    item.value = rowData[item.key] ?? item.value;
    // 设置name值
    if (item.state && item.key != 'attachment') item.state.name = formName;
    // 档案盒选项
    if (item.key == 'filesBoxId' && item.value) {
      item.state.params.folderId = props.data.storageLocation;
      item.state.params.typeId = props.data.filesType;
      proxy.$NotificationFormSub.pushParams({
        key: INITSERVE,
        value: {
          initKeys: 'filesBoxId',
          name: formName,
          configName: formName
        }
      });
    }
  });
}

onMounted(() => {
  // 监听form
  watch(
    () => modalRef.value.getDataFrom(),
    () => {
      emits('update:data', modalRef.value.getDataFrom());
    },
    { immediate: true }
  );
  // 监听导入更新
  watch(
    () => props.upDate,
    (newVal, oldVal) => {
      console.log('newVal', newVal);
      initData();
    }
  );
});
const isValidateFields = computed(() => {
  return modalRef.value.isValidateFields;
});
// 监听form
const subscribeSub = proxy.$NotificationFormSub
  .getParams()
  .pipe(filter((res) => res !== 0))
  .subscribe((item: any) => {
    if (item.key === SELECTSERVE && item.value.name == dyModalConfig.name) {
      if (item.value.key == 'filesBoxId') {
        const fileBox = findFolderById(item.value.data, item.value.value);
        setFormData({ boxName: fileBox.boxName, reelNo: fileBox.label });
        getDataById();
      } else if (item.value.key == 'storageLocation') {
        for (let i = 0; i < dyModalQuestions.length; i++) {
          if (dyModalQuestions[i].key == 'filesBoxId') {
            // 根据存放地点查询档案盒
            dyModalQuestions[i].value = null;
            dyModalQuestions[i].state.params.folderId = item.value?.value;
            dyModalQuestions[i].state.params.typeId = props.data.filesType;
          } else if (['reelNo', 'partNo'].includes(dyModalQuestions[i].key)) {
            dyModalQuestions[i].value = null;
          }
        }
      } else if (item.value.key == 'name') {
        const file = item.value.data.find((obj) => obj.id == item.value.value) || {};
        // 更新form表单
        initData(file);
        // 更新校验
        modalRef.value.initVerify();
      }
    }
    if (item.key === INPUTSERVE && item.value.name == dyModalConfig.name) {
      if (item.value.key == 'partNo' && item.value.value) {
        for (let i = 0; i < dyModalQuestions.length; i++) {
          if (dyModalQuestions[i].key == 'partNo') {
            dyModalQuestions[i].value = item.value.value;
          }
        }
      } else if (item.value.key == 'keyword') {
        for (let i = 0; i < dyModalQuestions.length; i++) {
          if (dyModalQuestions[i].key == 'keyword') {
            dyModalQuestions[i].value = item.value.value;
          }
        }
      } else if (item.value.key == 'summary') {
        for (let i = 0; i < dyModalQuestions.length; i++) {
          if (dyModalQuestions[i].key == 'summary') {
            dyModalQuestions[i].value = item.value.value;
          }
        }
      }
    }
  });

// 设置form值
function setFormData(assign) {
  for (let i = 0; i < dyModalQuestions.length; i++) {
    if (Object.prototype.hasOwnProperty.call(assign, dyModalQuestions[i].key)) {
      dyModalQuestions[i].value = assign[dyModalQuestions[i].key];
    }
  }
}

// 通过档案盒id补充件号
function getDataById() {
  // 根据导入的数据为准
  if (props.type == 'IMPORT') return;
  const dataFrom = modalRef.value.getDataFrom();
  if (!dataFrom.filesBoxId) return;
  const params = {
    id: dataFrom.filesBoxId
  };
  findListByBoxId(params).then((result) => {
    if (result.success) {
      const data = result.data;
      setFormData({
        partNo: data.partNo
      });
    }
  });
}
// 根据folder查找option
function findFolderById(arr: string | any[], folderId: any) {
  for (let i = 0; i < arr.length; i++) {
    const folder = arr[i];
    if (folder.id === folderId) {
      return folder;
    }
    if (folder.children && folder.children.length > 0) {
      const result = findFolderById(folder.children, folderId);
      if (result) {
        return result;
      }
    }
  }
  return null;
}

onBeforeUnmount(() => {
  subscribeSub && subscribeSub.unsubscribe();
  proxy.$NotificationFormSub.clearParams();
});

//组件对外公开方法
defineExpose({
  isValidateFields: isValidateFields //验证
});
</script>

<style lang="less" scoped></style>
